﻿
var dataInput = [];
var dataOutput = [];
var inputEditId = -1;
var outputEditId = -1;
var currentType = '';

$(document).ready(function () {

    initInput();
    initOutput();

    updateSubmitInputsLink();
    updateSubmitOutputsLink();

    $('a#input-modal-caller').fancybox({
        showCloseButton: false,
        fitToView: true,
        autoSize: true,
        closeClick: true,
        autoDimensions: false,
        width: 640,
        openEffect: 'none',
        padding: 0,
        onStart: function () {

            if (currentType == 'input') {
                if (inputEditId == -1)
                    $("#input-modal h1.header").text("Add Input");
                else
                    $("#input-modal h1.header").text("Edit Input");

            }
            else if (currentType == 'output') {
                if (outputEditId == -1)
                    $("#input-modal h1.header").text("Add Output");
                else
                    $("#input-modal h1.header").text("Edit Output");
            }

        },
        onClosed: function () {
            // Reset
            inputEditId = -1;
            outputEditId = -1;
            currentType = '';
            $("span#vldAmount").hide();
            $("#input-modal h1.header").empty();
        }
    });

    ////////////////////////////////////////////////////
    //// Input - MULTIPLE
    ///////////////////////////////////////////////////

    $("a#lnkAddMoreInputs").click(function () {
        resetInputModal();
        addInputRow();
        updateSubmitInputsLink();

    });
    $("a#lnkSubmitMultipleInputs").click(function () {
        submitMultipleInputs();
        updateSubmitInputsLink();

    });

    ////////////////////////////////////////////////////
    //// Output - MULTIPLE
    ///////////////////////////////////////////////////
    $("a#lnkAddMoreOutputs").click(function () {
        resetInputModal();
        addOutputRow();
        updateSubmitOutputsLink();
    });

    $("a#lnkSubmitMultipleOutputs").click(function () {
        submitMultipleOutputs();
        updateSubmitOutputsLink();

    });

    ////////////////////////////////////////////////////
    //// Regular
    ///////////////////////////////////////////////////




    $("a#lnkAddInput").click(function () {
        currentType = 'input';
        resetInputModal();
        $('a#input-modal-caller').click();

    });
    $("a#lnkAddOutput").click(function () {
        currentType = 'output';
        resetInputModal();
        $('a#input-modal-caller').click();

    });
});

////////////////////////////////////////////////////
//// Input - MULTIPLE
///////////////////////////////////////////////////

function submitMultipleInputs() {
    currentType = 'input';

    $(".multi-inputs .input-row").each(function (index) {
        var str = $("select#ddlFlowSystem", this).val();
        var item_id = $.trim(str.split('|')[1]);
        var item_type = $.trim(str.split('|')[0]);
        var item_name = $.trim($("select#ddlFlowSystem option:selected", this).text().split('-')[1]);


        if (!validateAmount_60pt($("input#txtAmountModal", this))) {
            $("span#vldAmount", this).show();
            return true;
        }
        else {
            $("span#vldAmount", this).hide();
        }

        var amount = $("input#txtAmountModal", this).val();
        var unit_id = $("select#ddlUnitModal", this).val();
        var unit_name = $("select#ddlUnitModal option:selected", this).text();

        unit_name = $.trim(unit_name.split('-')[1]);

        var row = {
            item_id: item_id,
            item_type: item_type,
            item_name: item_name,
            amount: amount,
            unit_id: unit_id,
            unit_name: unit_name
        };

        callbackFromInputModal(row);
        $(this).remove();
    });

    currentType = '';
}


function updateSubmitInputsLink() {
    if ($(".multi-inputs .input-row").length > 0) {
        $("a#lnkSubmitMultipleInputs").show();
    }
    else {
        $("a#lnkSubmitMultipleInputs").hide();
    }

}

function addInputRow() {

    var row = $("#input-modal").clone();
    var lnkClose = $("<a class='lnkClose'>Close</a>");

    lnkClose.click(function () {
        // Close current one
        $(this).parent().parent().remove();
        updateSubmitInputsLink();
    });

    row.find(".section").prepend(lnkClose);
    row.attr("class", "input-row");
    row.removeAttr("id");
    // row.find(".label").remove();
    row.find(".btns").remove();
    row.find("h1").remove();

    $("select#ddlFlowSystem", row).on('change', function () {
        var val = $(this).val();

        var item_type = $.trim(val.split('|')[0]);
        var item_id = $.trim(val.split('|')[1]);

        var select = $("select#ddlUnitModal", $(this).closest(".input-row"));
        filterUnitDropdown(item_type, item_id, select);
    });

    $(".multi-inputs").append(row);

}

////////////////////////////////////////////////////
//// Output - MULTIPLE
///////////////////////////////////////////////////

function submitMultipleOutputs() {
    currentType = 'output';

    $(".multi-outputs .output-row").each(function (index) {
        var str = $("select#ddlFlowSystem", this).val();
        var item_id = $.trim(str.split('|')[1]);
        var item_type = $.trim(str.split('|')[0]);
        var item_name = $.trim($("select#ddlFlowSystem option:selected", this).text().split('-')[1]);


        if (!validateAmount_60pt($("input#txtAmountModal", this))) {
            $("span#vldAmount", this).show();
            return true;
        }
        else {
            $("span#vldAmount", this).hide();
        }

        var amount = $("input#txtAmountModal", this).val();
        var unit_id = $("select#ddlUnitModal", this).val();
        var unit_name = $("select#ddlUnitModal option:selected", this).text();

        unit_name = $.trim(unit_name.split('-')[1]);

        var row = {
            item_id: item_id,
            item_type: item_type,
            item_name: item_name,
            amount: amount,
            unit_id: unit_id,
            unit_name: unit_name
        };

        callbackFromInputModal(row);
        $(this).remove();
    });

    currentType = '';
}


function updateSubmitOutputsLink() {
    if ($(".multi-outputs .output-row").length > 0) {
        $("a#lnkSubmitMultipleOutputs").show();
    }
    else {
        $("a#lnkSubmitMultipleOutputs").hide();
    }
}

function addOutputRow() {
    var row = $("#input-modal").clone();
    var lnkClose = $("<a class='lnkClose'>Close</a>");

    lnkClose.click(function () {
        // Close current one
        $(this).parent().parent().remove();
        updateSubmitOutputsLink();
    });

    row.find(".section").prepend(lnkClose);
    row.attr("class", "output-row");
    row.removeAttr("id");
    // row.find(".label").remove();
    row.find(".btns").remove();
    row.find("h1").remove();

    $("select#ddlFlowSystem", row).on('change', function () {
        var val = $(this).val();

        var item_type = $.trim(val.split('|')[0]);
        var item_id = $.trim(val.split('|')[1]);

        var select = $("select#ddlUnitModal", $(this).closest(".output-row"));
        filterUnitDropdown(item_type, item_id, select);
    });

    $(".multi-outputs").append(row);

}

function filterUnitDropdown(item_type, item_id, select) {

    // Get UnitGroup from current type - Flow / System
    var unit = LCA.ItemUnit.getUnitInfoByItem(item_type, item_id);

    // Get Unit list by UnitGroup
    var unitList = LCA.Unit.getUnitsByUnitGroup(unit.UnitGroupId);

    select.empty();

    for (var i = 0; i < unitList.length; i++) {
        var item = unitList[i];
        var option = $("<option value='" + item.UnitId + "'>" + item.UnitName + "</option>");
        select.append(option);
    }

    // Set selected
    select.val(unit.UnitId);
}

////////////////////////////////////////////////////
//// Input
///////////////////////////////////////////////////


function initInput() {
    var str = $("#txtInput").val();
    if (str != '') {
        dataInput = JSON.parse(str);
        for (var i = 0; i < dataInput.length; i++) {
            var item = dataInput[i];
            item.id = i;
        }
    }


    loadInputGrid();
}

function processInputData(row) {
    if (inputEditId != -1) {

        for (var i = 0; i < dataInput.length; i++) {
            var item = dataInput[i];
            if (item.id == inputEditId) {
                item.item_id = row.item_id;
                item.item_type = row.item_type;
                item.item_name = row.item_name;
                item.amount = row.amount;
                item.unit_id = row.unit_id;
                item.unit_name = row.unit_name;

                break;
            }
        }



    }
    else {
        var inputRow = {
            id: getNextId(dataInput),
            item_id: row.item_id,
            item_type: row.item_type,
            item_name: row.item_name,
            amount: row.amount,
            unit_id: row.unit_id,
            unit_name: row.unit_name
        };

        dataInput.push(inputRow);

    }


    updateInput();
    loadInputGrid();
    focusInputGrid();
}

function callbackFromInputModal(row) {
    if (currentType == 'input') {
        processInputData(row);
    }
    else if (currentType == 'output') {
        processOutputData(row);
    }

}

function updateInput() {
    $("#txtInput").val(JSON.stringify(dataInput));

}

function focusInputGrid() {
    $(window).scrollTop($('table#gridInput tr:last').offset().top);
}

function getNextId(data) {
    var max = -1;
    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        if (item.id > max)
            max = item.id;
    }

    return max + 1;
}

function editInputRow(id) {
    var selectedRow = null;
    for (var i = 0; i < dataInput.length; i++) {
        var item = dataInput[i];
        if (item.id == id) {
            selectedRow = item;
            break;
        }
    }

    inputEditId = id;
    currentType = 'input';

    resetInputModal();
    loadInputModal(selectedRow);
    $('a#input-modal-caller').click();
}

function deleteInputRow(id) {
    for (var i = 0; i < dataInput.length; i++) {
        var item = dataInput[i];
        if (item.id == id) {
            dataInput.splice(i, 1);
            break;
        }
    }

    updateInput();
    loadInputGrid();
    focusInputGrid();
}



function loadInputGrid() {

    $('table#gridInput').empty();

    var oTable = $('table#gridInput').dataTable({
        "bProcessing": true,
        "bDestroy": true,
        "bPaginate": false,
        "bAutoWidth": false,
        "bFilter": false,
        "aaSorting": [],
        "aaData": dataInput,
        "aoColumns": [

                    { "mDataProp": "item_name", "bSortable": true, "sTitle": "Name", "sClass": "cName", "bSearchable": true, "bVisible": true },
                    { "mDataProp": "amount", "bSortable": false, "sTitle": "Amount", "sClass": "cAmount", "bSearchable": true, "bVisible": true },
                    { "mDataProp": "unit_name", "bSortable": false, "sTitle": "Unit", "sClass": "cUnit", "bSearchable": true, "bVisible": true },
                    { "mDataProp": null, "bSortable": false, "sTitle": "", "sClass": "cDelete", "sDefaultContent": "<input id='btnEdit' class='button' type='button' value='Edit' /><input id='btnDelete' class='button' type='button' value='Delete' />", "bVisible": true }
                ],
        "fnCreatedRow": function (nRow, aData, iDataIndex) {
            // Assign id to 'tr'
            $(nRow).attr('id', aData.id);

            $('input#btnEdit', nRow).click(function (e) {
                editInputRow(aData.id);
            });

            $('input#btnDelete', nRow).click(function (e) {
                // console.log('btnDelete: ' + aData.id);
                if (confirm('Are you sure to delete this?')) {
                    deleteInputRow(aData.id);
                }
            });
        }


    });
}

////////////////////////////////////////////////////
//// Output
///////////////////////////////////////////////////

function initOutput() {

    var str = $("#txtOutput").val();
    if (str != '') {

        dataOutput = JSON.parse(str);
        for (var i = 0; i < dataOutput.length; i++) {
            var item = dataOutput[i];
            item.id = i;
        }
    }

    loadOutputGrid();
}

function processOutputData(row) {

    if (outputEditId != -1) {

        for (var i = 0; i < dataOutput.length; i++) {
            var item = dataOutput[i];
            if (item.id == outputEditId) {
                item.item_id = row.item_id;
                item.item_type = row.item_type;
                item.item_name = row.item_name;
                item.amount = row.amount;
                item.unit_id = row.unit_id;
                item.unit_name = row.unit_name;

                break;
            }
        }



    }
    else {
        var inputRow = {
            id: getNextId(dataOutput),
            item_id: row.item_id,
            item_type: row.item_type,
            item_name: row.item_name,
            amount: row.amount,
            unit_id: row.unit_id,
            unit_name: row.unit_name
        };

        dataOutput.push(inputRow);

    }


    updateOutput();
    loadOutputGrid();
    focusOutputGrid();
}

function editOutputRow(id) {
    var selectedRow = null;
    for (var i = 0; i < dataOutput.length; i++) {
        var item = dataOutput[i];
        if (item.id == id) {
            selectedRow = item;
            break;
        }
    }

    outputEditId = id;
    currentType = 'output';

    resetInputModal();
    loadInputModal(selectedRow);
    $('a#input-modal-caller').click();
}

function deleteOutputRow(id) {
    for (var i = 0; i < dataOutput.length; i++) {
        var item = dataOutput[i];
        if (item.id == id) {
            dataOutput.splice(i, 1);
            break;
        }
    }

    updateOutput();
    loadOutputGrid();
    focusOutputGrid();
}

function updateOutput() {
    $("#txtOutput").val(JSON.stringify(dataOutput));
}

function focusOutputGrid() {
    $(window).scrollTop($('table#gridOutput tr:last').offset().top);
}

function loadOutputGrid() {
    $('table#gridOutput').empty();

    var oTable = $('table#gridOutput').dataTable({
        "bProcessing": true,
        "bDestroy": true,
        "bPaginate": false,
        "bAutoWidth": false,
        "bFilter": false,
        "aaSorting": [],
        "aaData": dataOutput,
        "aoColumns": [

                    { "mDataProp": "item_name", "bSortable": true, "sTitle": "Name", "sClass": "cName", "bSearchable": true, "bVisible": true },
                    { "mDataProp": "amount", "bSortable": false, "sTitle": "Amount", "sClass": "cAmount", "bSearchable": true, "bVisible": true },
                    { "mDataProp": "unit_name", "bSortable": false, "sTitle": "Unit", "sClass": "cUnit", "bSearchable": true, "bVisible": true },
                    { "mDataProp": null, "bSortable": false, "sTitle": "", "sClass": "cDelete", "sDefaultContent": "<input id='btnEdit' class='button' type='button' value='Edit' /><input id='btnDelete' class='button' type='button' value='Delete' />", "bVisible": true }
                ],
        "fnCreatedRow": function (nRow, aData, iDataIndex) {
            // Assign id to 'tr'
            $(nRow).attr('id', aData.id);

            $('input#btnEdit', nRow).click(function (e) {
                editOutputRow(aData.id);
            });

            $('input#btnDelete', nRow).click(function (e) {
                // console.log('btnDelete: ' + aData.id);
                if (confirm('Are you sure to delete this?')) {
                    deleteOutputRow(aData.id);
                }
            });
        }


    });
}